package com.utils;

import com.os.OS;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @author rkc
 * @date 2022/8/23 12:12
 */
@Slf4j
public class ProcessUtil {

    /**
     * 根据pid关闭进程
     * @param pid 进程的PID
     */
    public static boolean killProcessByPid(long pid) {
        if (pid == -1) {
            throw new RuntimeException("Pid ==" + pid);
        }
        String command = OS.isWindows() ? "cmd.exe /c taskkill /PID " + pid + " /F /T " : "kill -9 " + pid;
        boolean result = false;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            log.error("{}", e.getMessage());
            return false;
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                log.info("kill PID return info -----> " + line);
            }
            result = true;
        } catch (Exception e) {
            log.info("杀进程出错：", e);
        } finally {
            process.destroy();
        }
        return result;
    }
}

